package com.huahai.manager.websocket.disruptor;

import com.huahai.manager.websocket.model.PictureEditMessageDTO;
import org.springframework.web.socket.WebSocketSession;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.huahai.manager.websocket.PictureEditHandler;
import com.huahai.manager.websocket.enums.PictureEditMessageTypeEnum;
import com.huahai.manager.websocket.model.PictureEditMessageVO;
import com.huahai.pojo.entity.User;
import com.huahai.service.UserService;
import com.lmax.disruptor.WorkHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;

import javax.annotation.Resource;

/**
 * 图片编辑事件处理器（消费者）
 *
 * @author huahai
 */
@Component
@Slf4j
public class PictureEditEventWorkHandler implements WorkHandler<PictureEditEvent> {

    @Resource
    private PictureEditHandler pictureEditHandler;

    @Resource
    private UserService userService;

    /**
     * 定义处理图片编辑事件方法
     *
     * @param pictureEditEvent 图片编辑事件
     * @throws Exception
     */
    @Override
    public void onEvent(PictureEditEvent pictureEditEvent) throws Exception {
        // 从事件中取值
        PictureEditMessageDTO pictureEditMessageDTO = pictureEditEvent.getPictureEditMessageDTO();
        WebSocketSession session = pictureEditEvent.getSession();
        User user = pictureEditEvent.getUser();
        Long pictureId = pictureEditEvent.getPictureId();

        // 转化消息类型为枚举
        String type = pictureEditMessageDTO.getType();
        PictureEditMessageTypeEnum pictureEditMessageTypeEnum = PictureEditMessageTypeEnum.valueOf(type);

        // 处理不同状态的消息
        switch (pictureEditMessageTypeEnum) {
            case ENTER_EDIT:
                pictureEditHandler.handleEnterEditMessage(pictureEditMessageDTO, session, pictureId, user);
                break;
            case EDIT_ACTION:
                pictureEditHandler.handleEditActionMessage(pictureEditMessageDTO, session, pictureId, user);
                break;
            case EXIT_EDIT:
                pictureEditHandler.handleExitEditMessage(pictureEditMessageDTO, session, pictureId, user);
                break;
            default:
                // 默认发送错误消息
                PictureEditMessageVO pictureEditMessageVO = new PictureEditMessageVO();
                pictureEditMessageVO.setType(PictureEditMessageTypeEnum.ERROR.getValue());
                pictureEditMessageVO.setMessage("消息类型错误");
                pictureEditMessageVO.setUser(userService.getUserVO(user));
                // 获取处理 JSON 精度丢失的序列化器
                ObjectMapper objectMapper = PictureEditHandler.getObjectMapper();
                String errorMessage = objectMapper.writeValueAsString(pictureEditMessageVO);
                session.sendMessage(new TextMessage(errorMessage));
                break;
        }
    }
}
